//
//  UserAccountViewModel.swift
//  SinaWebo
//
//  Created by mis on 16/3/19.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    
    let account: UserAccount?
    
    var userLogin: Bool {
        return account?.access_token != nil
    }
    
    var access_token: String? {
        return account?.access_token
    }
    
    var name: String? {
        return account?.name
    }
    
    var headURL: NSURL? {
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    
    override init() {
        account = UserAccount.loadAccount()
    }
    
    func loadAccessToken(code: String, finished: (error: NSError?)-> ()) {
        let urlStr = "oauth2/access_token"
        let paratemers = ["client_id": client_id,"client_secret":client_secret,"grant_type" : "authorization_code","code":code,"redirect_uri":redirect_uri]
        NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlStr, parameters: paratemers) { (result, error) -> () in
            if error != nil {
                print(error)
                finished(error: error)
                return
            }
            let account = UserAccount(dict: result!)
            self.loadUserInfo(account, finished: finished)
        }
    }
    
    private func loadUserInfo(account: UserAccount, finished: (error: NSError?) -> ()) {
        let urlStr = "2/users/show.json"
        let paratemers = ["access_token":account.access_token!, "uid": account.uid!]
//        let manager = AFHTTPSessionManager()
//        manager.GET(urlStr, parameters: paratemers, progress: nil, success: { (_, result) -> Void in
//            if let dict = result as? [String: AnyObject] {
//                print(dict)
//                account.name = dict["name"] as? String
//                account.avatar_large = dict["avatar_large"] as? String
//                account.saveAccount()
//                finished(error: nil)
//            }
//            }) { (_, error) -> Void in
//                finished(error: error)
//        }
        
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlStr, parameters: paratemers) { (result, error) -> () in
            if error != nil {
                print(error)
                finished(error: error)
                return
            }
            account.name = result!["name"] as? String
            account.avatar_large = result!["avatar_large"] as? String
            account.saveAccount()
            finished(error: nil)
        }
    }
}
